package cn.xspace.wnx.service;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.hyphenate.EMCallBack;
import com.xspace.android.xafcommon.util.Constants;
import com.xspace.android.xafcommon.util.LogUtil;
import com.xspace.android.xafcommon.util.ModuleConfig;

import cn.xspace.chatui.bean.MessageEntity;
import cn.xspace.chatui.bean.MsgRecordEntity;
import cn.xspace.library.util.BldNavigation;
import cn.xspace.library.util.MyInfoUtil;
import cn.xspace.wnx.activity.MsgForwardActivity;
import cn.xspace.wnx.db.WNXDBManager;
import cn.xspace.wnx.util.HuanXinHelper;


/**
 * Created by liuchen on 2016/11/11.
 */

public class WnxService extends IntentService {

    public static String XMPP_LOGIN = "xmppLogin";
    public static String XMPP_LOGIN_OUT = "xmppLoginOut";
    public static String HX_LOGIN = "huanxinLogin";
    public static String MsgForward = "msgForward";
    private Context mContext;

    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     */
    public WnxService() {
        super("WnxService");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
    }
    //启动环信，xmpp推送服务

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        String action = intent.getStringExtra(ModuleConfig.OPERATION);
        LogUtil.d(action);
        if (XMPP_LOGIN.equals(action)) { //XMPP推送服务,替换为环信,暂停该服务
//            xmppLogin()
//                    .subscribeOn(Schedulers.io())
//                    .subscribe(xmppSub);

//            Intent mIntent = new Intent(mContext, IMChatService.class);
//            startService(mIntent);
//            Intent mReIntent = new Intent(mContext, ReConnectService.class);
//            startService(mReIntent);
        } else if (HX_LOGIN.equals(action)) { //环信Im聊天服务

            WNXDBManager.getInstance().closeDB();
            HuanXinHelper.getInstance().login(MyInfoUtil.getMyUserid(mContext), "", null);
        } else if (XMPP_LOGIN_OUT.equals(action)) {
//            XmppConnectionManager.getInstance().disconnect();
//            // 推送服务
//            Intent chatServer = new Intent(mContext, IMChatService.class);
//            mContext.stopService(chatServer);
            HuanXinHelper.getInstance().logout(false, new EMCallBack() {

                @Override
                public void onSuccess() {
                    LogUtil.d("wubaojie>>>onSuccess: 环信正常退出");
                }

                @Override
                public void onProgress(int progress, String status) {
                    LogUtil.d(status);
                }

                @Override
                public void onError(int code, String message) {

                }
            });
        } else if (MsgForward.equals(action)) {
            //Url分享
            String mTitle = intent.getStringExtra(BldNavigation.ForwardTitle);
            String mUrl = intent.getStringExtra(BldNavigation.ForwardUrl);
            MsgRecordEntity turnBean = new MsgRecordEntity();
            turnBean.msg_content_type = MessageEntity.ContentType.OTHER.toNumber();
            turnBean.msg_content = mTitle + Constants.CHAR_SPECIAL + mUrl;
            Bundle mBundle = new Bundle();
            mBundle.putSerializable(MsgForwardActivity.FORWARD_ENTITY, turnBean);

            Intent mIntent = new Intent(mContext, MsgForwardActivity.class);
            mIntent.putExtra(BldNavigation.KEY_BUNDLER, mBundle);
            mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mContext.startActivity(mIntent);
            //转发
//            Navigator.startForwardActivity(mContext, mBundle);
        }
    }

//    public Observable xmppLogin() {
//        // xmpp登录
//        return Observable.create(new Observable.OnSubscribe<Object>() {
//            @Override
//            public void call(Subscriber<? super Object> subscriber) {
//                try {
//                    XMPPConnection connection = XmppConnectionManager.getInstance().getConnection();
//
//                    connection.addConnectionListener(new XmppConnectListener(mContext));
//                    String userid = MyInfoUtil.getMyUserid(mContext);
//                    String pasword = AppUtils.MD5((String) PreferencesUtils.getPfValue(BaseAppliction.mInstance,
// Constants
//                            .ACCOUNT_PASSWORD_KEY,
//                            String.class.getName()), false);
//                    LogUtil.d(userid);
//                    LogUtil.d(pasword);
//                    if (connection.isConnected()) {
//                        LogUtil.e("wubaojie--->:第一次启动xmpp服务时已经连接");
//                    } else {
//                        LogUtil.e("wubaojie--->:第一次启动xmpp服务时连接失败");
//                    }
//                    if (!connection.isAuthenticated()) {
//                        connection.login(userid, pasword, XmppConnectionManager.ACCOUNT_RESOURCE_KEY); // 登录
//                    }
//
//                    connection.sendPacket(new Presence(Presence.Type.available));
//                    PingManager.getInstanceFor(connection).setPingIntervall(30);
//                    subscriber.onNext("XMPP_LOGIN_SUCCESS");
//                } catch (XMPPException xee) {
//                    xee.printStackTrace();
//                    int errorCode = 0;
//                    if (xee instanceof XMPPException) {
//                        XMPPException xe = xee;
//                        final XMPPError error = xe.getXMPPError();
//                        LogUtil.d(error.toString());
//                        if (error != null) {
//                            errorCode = error.getCode();
//                        }
//                        LogUtil.d(errorCode + "");
//                        if (errorCode == 401) {
//                            subscriber.onError(new HttpException(mContext.getString(R.string
//                                    .message_invalid_username_password), errorCode));
//                        } else if (errorCode == 403) {
//                            subscriber.onError(new HttpException(mContext.getString(R.string
//                                    .message_server_unavailable), errorCode));
//                        } else {
//                            subscriber.onError(new HttpException(mContext.getString(R.string.unrecoverable_error),
//                                    errorCode));
//                        }
//                    } else {
//                        subscriber.onError(new HttpException(mContext.getString(R.string.unknow_error), errorCode));
//                    }
//                } catch (Exception e) {
////                    subscriber.onError(new HttpException(mContext.getString(R.string.unknow_error), errorCode));
//                    LogUtil.d("1111111");
//                    LogUtil.d(e.getMessage());
//                    e.printStackTrace();
//                } finally {
//                    LogUtil.d("2222222");
//                }
//            }
//        });
//    }

//    Subscriber xmppSub = new Subscriber() {
//        @Override
//        public void onCompleted() {
//
//        }
//
//        @Override
//        public void onError(Throwable e) {
//            T.showShort(mContext, e.getMessage());
//        }
//
//        @Override
//        public void onNext(Object o) {
//            LogUtil.d(o.toString());
//            //登录成功，启动XMpp服务
//            Intent mIntent = new Intent(mContext, IMChatService.class);
//            startService(mIntent);
//            Intent mReIntent = new Intent(mContext, ReConnectService.class);
//            startService(mReIntent);
//        }
//    };
}
